import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '../services/api'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || null)

  const isAuthenticated = computed(() => {
    const hasToken = !!token.value
    console.log('认证状态计算: hasToken=', hasToken, 'user=', user.value)
    return hasToken
  })

  const login = async (username, password) => {
    console.log('开始登录流程...', username)
    
    try {
      // 使用 FormData 发送登录请求
      const formData = new FormData()
      formData.append('username', username)
      formData.append('password', password)
      
      console.log('发送登录请求...')
      const response = await api.post('/token', formData)
      console.log('登录响应:', response.data)
      
      // 保存 token
      token.value = response.data.access_token
      localStorage.setItem('token', token.value)
      console.log('Token 已保存:', token.value ? `${token.value.substring(0, 20)}...` : '空')
      
      // 获取用户信息
      console.log('获取用户信息...')
      const userResponse = await api.get('/users/me/')
      user.value = userResponse.data
      console.log('用户信息已保存:', user.value)
      
      return true
    } catch (error) {
      console.error('登录过程中出错:', error)
      // 清除可能的部分状态
      token.value = null
      user.value = null
      localStorage.removeItem('token')
      throw error
    }
  }

  const logout = () => {
    console.log('执行登出')
    user.value = null
    token.value = null
    localStorage.removeItem('token')
    console.log('登出完成，认证状态:', isAuthenticated.value)
  }

  const checkAuth = async () => {
    console.log('检查认证状态...')
    if (token.value) {
      try {
        console.log('有 token，验证用户信息...')
        const response = await api.get('/users/me/')
        user.value = response.data
        console.log('用户信息验证成功:', user.value)
        return true
      } catch (error) {
        console.error('验证用户信息失败:', error)
        // 清除无效的 token
        logout()
        return false
      }
    } else {
      console.log('没有 token，用户未登录')
      return false
    }
  }

  return {
    user,
    token,
    isAuthenticated,
    login,
    logout,
    checkAuth
  }
})
